
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_is_know_dialog.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/set_each_day_onoff_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:upgrade_flutter/upgrade_flutter.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'binding_terminal/binding_terminal_view_model.dart';
import 'new_terminal_list/bean/common_terminal_settings_response_bean.dart';
import 'new_terminal_list/new_terminal_list_view_model.dart';

///设置定时开关机页面
class SetAutoOnOffByEachDayPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "SetAutoOnOffByEachDayPage";
  final ComAutoSwitchBean autoBean;
  final Function(ComAutoSwitchBean autoBean) onSet;
  final String hsn;
  final int rcaid;
  final VoidCallback callback;
  final bool showOffHint;

  const SetAutoOnOffByEachDayPage({
    Key key,
    this.autoBean,
    this.onSet,
    this.hsn,
    this.rcaid,
    this.callback,
    this.showOffHint,
  }) : super(key: key);

  @override
  _SetAutoOnOffByEachDayPageState createState() => _SetAutoOnOffByEachDayPageState();

  ///跳转方法
  ///返回Map
  static Future<Map<String,dynamic>> navigatorPush(
      BuildContext context, ComAutoSwitchBean autoBean, Function onSet,
      {String hsn, int rcaid, VoidCallback callback, bool showOffHint}) {
    return RouterUtils.routeForFutureResult(
      context,
      SetAutoOnOffByEachDayPage(
        autoBean:autoBean,
        onSet:onSet,
        hsn:hsn,
        rcaid:rcaid,
        callback:callback,
        showOffHint:showOffHint,
      ),
      routeName: SetAutoOnOffByEachDayPage.ROUTER,
    );
  }
}

class _SetAutoOnOffByEachDayPageState extends BaseState<SetAutoOnOffByEachDayPage>{
  ComAutoSwitchBean _autoBean;
  NewTerminalListViewModel _commonViewModel;
  BindingTerminalViewModel _singleViewModel;
  bool _initFlag = false;
  @override
  void initState() {
    super.initState();
    if(widget?.autoBean != null){
      _autoBean = widget?.autoBean;
    }else{
      _autoBean = new ComAutoSwitchBean();
    }
    _commonViewModel = NewTerminalListViewModel(this);
    _singleViewModel = BindingTerminalViewModel(this);

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if((widget?.showOffHint??false) && !_initFlag){
        CommonISeeDialog.navigatorPushDialog(context, title: "提示",
            content:"当前显示屏已关机，定时设置将在开机后生效");
        _initFlag = true;
      }
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: _toMainWidget(),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }


  Widget _toMainWidget(){
    return Column(
      children: [
        _toTopBarWidget(),
        Expanded(child: _toWeekTimeListWidget()),
      ],
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "定时开关机",
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      isShowBack: true,
      rightWidget: GestureDetector(
        onTap: ()async{
          bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: "确定关闭定时开关机功能？",
            cancelText: "取消",
            confirmText: "关闭",
            confirmBgColor: ThemeRepository.getInstance()
                .getMinorRedColor_F95355(),);
          if (result ?? false) {
            _autoBean.autoOnoff = "00";
            if(StringUtils.isNotEmpty(widget?.hsn??"")){
              //代表是单终端
              _singleViewModel.saveAutoOnOffByWeek(context, widget?.hsn,
                  widget?.rcaid, _autoBean, callback: (){
                    RouterUtils.pop(context);
                    if(widget?.callback != null){
                      widget?.callback?.call();
                    }
                  });
              // RouterUtils.pop(context);
            }else{
              _commonViewModel.saveAutoOnOffByWeek(context, _autoBean, () {
                widget?.onSet?.call(_autoBean);
                RouterUtils.pop(context);
                if(widget?.callback != null){
                  widget?.callback?.call();
                }
              });
            }

          }
        },
        child: Container(
          padding: EdgeInsets.only(left: 15),
          height: 44,
          alignment: Alignment.center,
          child: Text(
            "关闭功能",
            style: TextStyle(
                fontSize: 14,
                height: 1.2,
                color: ThemeRepository.getInstance().getMinorRedColor_F95355()
            ),
          ),
        ),
      ),
    );
  }

  Widget _toWeekTimeListWidget(){
    return ListView(
      padding: EdgeInsets.zero,
      children: [
        _toWeekTimeItemWidget("周一", _autoBean?.autoMon, _autoBean?.monTime),
        _toWeekTimeItemWidget("周二", _autoBean?.autoTues, _autoBean?.tuesTime),
        _toWeekTimeItemWidget("周三", _autoBean?.autoWed, _autoBean?.wedTime),
        _toWeekTimeItemWidget("周四", _autoBean?.autoThur, _autoBean?.thurTime),
        _toWeekTimeItemWidget("周五", _autoBean?.autoFri, _autoBean?.friTime),
        _toWeekTimeItemWidget("周六", _autoBean?.autoSat, _autoBean?.satTime),
        _toWeekTimeItemWidget("周日", _autoBean?.autoSun, _autoBean?.sunTime),
        SizedBox(height: 21,),
        _toHolidaySettingsWidget(_autoBean?.restflg??""),
      ],
    );
  }

  int _getActiveCount(){
    int activeCount = 0;
    if("01" == _autoBean?.autoMon){
      activeCount = activeCount + 1;
    }
    if("01" == _autoBean?.autoTues){
      activeCount = activeCount + 1;
    }
    if("01" == _autoBean?.autoWed){
      activeCount = activeCount + 1;
    }
    if("01" == _autoBean?.autoThur){
      activeCount = activeCount + 1;
    }
    if("01" == _autoBean?.autoFri){
      activeCount = activeCount + 1;
    }
    if("01" == _autoBean?.autoSat){
      activeCount = activeCount + 1;
    }
    if("01" == _autoBean?.autoSun){
      activeCount = activeCount + 1;
    }
    return activeCount;
  }

  Widget _toWeekTimeItemWidget(String title, String status, String time){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()async{
        SetEachDayOnOffPage.navigatorPush(context,
            getStartOrEndTime(time, 0),
            getStartOrEndTime(time, 1),
            title,
                (onOff, onOffTime){
                if("11" == onOff){
                  //代表直接关闭
                  _autoBean.autoOnoff = "00";
                  if(StringUtils.isNotEmpty(widget?.hsn??"")){
                    //代表是单终端
                    _singleViewModel.saveAutoOnOffByWeek(context,
                        widget?.hsn, widget?.rcaid,
                        _autoBean, callback: (){
                          widget?.onSet?.call(_autoBean);
                          if(widget?.callback != null){
                            widget?.callback?.call();
                          }
                          RouterUtils.pop(context);
                        });
                  }else{
                    _commonViewModel.saveAutoOnOffByWeek(context, _autoBean, () {
                      widget?.onSet?.call(_autoBean);
                      RouterUtils.pop(context);
                      if(widget?.callback != null){
                        widget?.callback?.call();
                      }
                    });
                  }

                }else{
                  _updateTime(title, onOff, onOffTime);
                  if(StringUtils.isNotEmpty(widget?.hsn??"")){
                    //代表是单终端
                    _singleViewModel.saveAutoOnOffByWeek(context, widget?.hsn, widget?.rcaid, _autoBean);
                  }else{
                    _commonViewModel.saveAutoOnOffByWeek(context, _autoBean, () { });
                  }
                }
                setState(() {
                });

            },
            _getActiveCount()
        );
      },
      child: Container(
        height: 50,
        alignment: Alignment.center,
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        padding: EdgeInsets.symmetric(horizontal: 15),
        child: Row(
          children: [
            Text(
              title,
              style: TextStyle(
                  fontSize: 14,
                  height: 1.2,
                  color: ThemeRepository.getInstance().getTextColor_D0E0F7()
              ),
            ),
            Spacer(),
            Text(
              (StringUtils.isNotEmpty(time) && "01" == status)?(time.replaceAll("-", "~")):"不自动开机",
              style: TextStyle(
                  fontSize: 14,
                  height: 1.2,
                  color: (StringUtils.isNotEmpty(time) && "01" == status)?ThemeRepository.getInstance().getPrimaryColor_1890FF():ThemeRepository.getInstance().getHintGreenColor_5E687C()
              ),
            ),
            SizedBox(width: 9,),
            Image.asset(
              "images/index_arrow_ico.png",
              width: 6,
            ),
          ],
        ),
      ),
    );
  }

  _updateTime(String title, String status, String time){
    switch(title){
      case "周一":
        _autoBean?.monTime = time;
        _autoBean?.autoMon = status;
        break;
      case "周二":
        _autoBean?.tuesTime = time;
        _autoBean?.autoTues = status;
        break;
      case "周三":
        _autoBean?.wedTime = time;
        _autoBean?.autoWed = status;
        break;
      case "周四":
        _autoBean?.thurTime = time;
        _autoBean?.autoThur = status;
        break;
      case "周五":
        _autoBean?.friTime = time;
        _autoBean?.autoFri = status;
        break;
      case "周六":
        _autoBean?.satTime = time;
        _autoBean?.autoSat = status;
        break;
      case "周日":
        _autoBean?.sunTime = time;
        _autoBean?.autoSun = status;
        break;
    }
  }

  DateTime getStartOrEndTime(String autoOffTime,int index){
    if(StringUtils.isEmpty(autoOffTime) || index == null ||index <0 || index > 1){
      return null;
    }
    List<String> timeList = autoOffTime.split("-");
    if(timeList == null || timeList.length != 2){
      return null;
    }
    String time = timeList.elementAt(index);
    if(StringUtils.isEmpty(time)){
      return null;
    }
    List<String> hourMinList = time.split(":");
    if(hourMinList == null || hourMinList.length != 2){
      return null;
    }
    final DateTime nowDateTime = DateTime.now();

    return DateTime(nowDateTime.year, nowDateTime.month, nowDateTime.day,int.tryParse(hourMinList.elementAt(0)),int.tryParse(hourMinList.elementAt(1)));
  }


  Widget _toHolidaySettingsWidget(String status){
    return Container(
      height: 50,
      alignment: Alignment.centerLeft,
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      padding: EdgeInsets.symmetric(horizontal: 15),
      child: Row(
        children: [
          Text(
            "国家规定工作日自动开关机",
            style: TextStyle(
              fontSize: 12,
              color: ThemeRepository.getInstance().getTextColor_D0E0F7()
            ),
          ),
          Spacer(),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: (){
              setState(() {
                _autoBean?.restflg = ("00" == status)?"01":"00";
              });
              if(StringUtils.isNotEmpty(widget?.hsn??"")){
                //代表是单终端
                _singleViewModel.saveAutoOnOffByWeek(context, widget?.hsn, widget?.rcaid, _autoBean, noToast: true);
              }else{
                _commonViewModel.saveAutoOnOffByWeek(context, _autoBean, () { }, noToast: true);
              }
            },
            child: Image.asset(
              ("00" == _autoBean?.restflg??"01")
                  ? "images/icon_open.png"
                  :"images/icon_close.png",
              width: 36,
            ),
          ),
        ],
      ),
    );
  }
}


